
export interface Action {
    type: string;
    payload?: any;
}
export const createStore = function <T extends Record<string, any>>(
    reducer: (state: T, action: Action) => T,
    initState: T
) {
    let listeners: Array<() => void> = [];
    let state = initState;

    function subscribe(handler: () => void) {
        // 我们希望，订阅了这个Data 的函数handler ，在 Data 改变的时候，handler 要执行一下
        listeners.push(handler);
    };

    function dispatch(action: Action) {
        // immutable 
        const currentState: T = reducer(state, action);
        state = currentState;
        listeners.forEach(h => h())
    }


    function getState() {
        return state;
    }

    return { subscribe, dispatch, getState }
}

export const combineReducer = <T extends Record<string, any>>(
    reducers: { [key in keyof T]: (state: T[key], action: Action) => T[key] }
) => {
    const keys: Array<keyof T> = Object.keys(reducers); // 先拿到 [counter, info]
    return function (state: T, action: Action) {
        let nextState: T = Object.assign({}, state);
        keys.forEach((key) => {
            const reducer = reducers[key]; //counterReducer, infoReducer
            const prev = state[key];  // { count: 1, }
            const next = reducer(prev, action); //   { count: 2, }
            nextState[key] = next; //  { counter: { count: 2 },  ... }
        })
        return nextState;
    }
}